package com.vce.web.security;

import javax.servlet.*;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import com.vce.SecurityManager;
import org.springframework.web.filter.OncePerRequestFilter;
/**
 * Created by IntelliJ IDEA.
 * User: Larry Ruiz
 * Date: 03-13-2007
 * Time: 07:58:16 PM
 * To change this template use File | Settings | File Templates.
 *
 * @author Larry Ruiz
 */
public class ForceAuthenticationFilter extends OncePerRequestFilter implements Filter {
    private String dontApplyFor;
    private String entryPoint;
    private boolean enable = true;
    private SecurityManager securityManager;
    
    public void setSecurityManager(SecurityManager securityManager){
        this.securityManager = securityManager;
    }    
    
    public void setDontApplyFor(String dontApplyFor){
        this.dontApplyFor = dontApplyFor;
    }
    
    public void setEntryPoint(String entryPoint){
        this.entryPoint = entryPoint;
    }
    
    public void setEnable(boolean enable){
        this.enable = enable;
    }
    
    public boolean shouldNotFilter(HttpServletRequest request){
        String uri = request.getRequestURI();
        if(!enable || securityManager.getCurrentUser() != null
            || uri.endsWith(entryPoint)){
            return true;
        }
        
        if(dontApplyFor == null){
            return false;
        }
        
        int length = request.getContextPath().length();
        uri = uri.substring(length);        
        return uri.matches(dontApplyFor);
    }
    
    public String getRedirectUrl(HttpServletRequest request, String loginFormUrl){
        String contextPath = request.getContextPath();
        
        //boolean inHttp = "http".equals(request.getScheme());
        //boolean inHttps = "https".equals(scheme.toLowerCase());
        boolean includePort = true;
        
        if (request.getServerPort() == 80) {
            includePort = false;
        } else if (request.getServerPort() == 443) {
            includePort = false;
        }
        
        String redirectUrl = request.getScheme() + "://" + request.getServerName() + ((includePort) ? (":" + request.getServerPort()) : "") + contextPath
                + loginFormUrl;
        
        return redirectUrl;
    }
    
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws ServletException, IOException {
        response.sendRedirect(response.encodeRedirectURL(getRedirectUrl(request, entryPoint)));
    }
}
